package com.card323.crpg;

import java.util.Hashtable;

import com.card323.crpg.io.MessageReceiver;
import com.card323.crpg.io.MessageReceiverFactory;
import com.card323.crpg.io.MessageSender;
import com.card323.crpg.io.MessageSenderFactory;
import com.card323.crpg.io.swing.IOJFrame;

public class PlayerManager {

	private PlayerManager() {

	}

	private static class SingletonHolder {
		public static final PlayerManager instance = new PlayerManager();
	}

	public static PlayerManager getInstance() {
		return SingletonHolder.instance;
	}

	public Hero init_player(String email,String client_type ) {
		if (get_hero(email) == null) {
			Hero hero = load_hero(email);
			add_hero(email, hero);
			init_io(hero,email,client_type);
			return hero;
		} else {
			return get_hero(email);
		}
	}

	private void init_io(Hero hero, String email, String client_type) {

		MessageSender msender = null;
		MessageReceiver mreceiver = null;

		if (client_type.equals("msn")) {
			msender = MessageSenderFactory.getInstance().get_message_sender(
					"msn", email);

			mreceiver = MessageReceiverFactory.getInstance()
					.get_message_receiver("msn", email);
		}
		if (client_type.equals("console")) {
			msender = MessageSenderFactory.getInstance().get_message_sender(
					"console", email);

			mreceiver = MessageReceiverFactory.getInstance()
					.get_message_receiver("console", email);
		}
		if (client_type.equals("swing")) {
			IOJFrame frame = new IOJFrame();
			_hash_provider.put(email, frame);
			msender = frame;
			mreceiver = frame;
			hero.set_allies_listener();
			frame.setVisible(true);

		}
		hero.set_mreceiver(mreceiver);
		hero.set_msender(msender);

	}

	private void add_hero(String email, Hero h) {
		_hash_hero.put(email, h);
	}

	private Hero load_hero(String email) {
		// TODO
		return new Hero(email);
	}

	protected Hashtable<String, Hero> _hash_hero = new Hashtable<String, Hero>();

	private Hero get_hero(String email) {
		return _hash_hero.get(email);
	}

	public boolean is_player_inited(String email) {

		return _hash_hero.containsKey(email);
	}

	protected Hashtable<String, ListenerProvider> _hash_provider = new Hashtable<String, ListenerProvider>();
	
	public ListenerProvider get_listener_provider(String email) {
		// TODO Auto-generated method stub
		return _hash_provider.get(email);
	}
}
